<template>
  <div>
    <el-form ref="stuForm" size="small" :model="entity" :rules="rules" label-width="120px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="entity.name" placeholder="姓名" />
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model.number="entity.age" placeholder="年龄" />
      </el-form-item>
      <el-form-item label="出生日期" prop="birth">
        <el-date-picker v-model="entity.birth" type="date" placeholder="出生日期" style="width: 100%;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  props:{
    entityId : {type : Number, default: 0}
  },
  data() {
    return {
      entity: {
        name: '',
        age: '',
        birth: '',
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' }
        ],
        birth: [
          { required: true, message: '请输入出生日期', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadEntity();
  },
  methods: {
    loadEntity(){
      if(this.entityId > 0){
        request({ url: '/student/getstudent', data: {id : this.entityId} }).then( res =>{
          this.entity = res.data
        })
      }
    },
    onSubmit(){
      this.$refs['stuForm'].validate((valid) => {
        if(valid){
          request({
            url: '/student/addeditstudent',
            data: this.entity
          }).then( res =>{
            if(res.code === "200"){
              this.$message.success(res.msg)
              this.$emit('update:visible', false);  //关闭弹窗
              //触发事件总线，让列表界面更新数据
              this.entityId > 0 ? this.$EventBus.$emit("stuedit", {}):this.$EventBus.$emit("stuadd", {})
            }else{
              this.$message.error(res.msg);
            }
          })
        }else{
          console.log('error submit!!');
          return false;
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
